<?php

class Picture {

    public static function uploadFromURL($url, $path) {

        global $VALID_IMG_TYPES;
        global $VALID_IMG_TYPES_STR;

        $url = DBUrl::create($url);

        $size = remoteSize($url);

        if($size > MUSDB_MAX_IMAGE_SIZE)
            throw new Exception(_('Image can be ') . (MUSDB_MAX_IMAGE_SIZE / 1024) . _(' KB max.'));

        $contents = file_get_contents($url);

        $data = getimagesize($url);

        if(!in_array($data[2], $VALID_IMG_TYPES))
            throw new Exception(_('Valid image types are ') . $VALID_IMG_TYPES_STR.'.');

        switch($data[2]) {
            case IMAGETYPE_JPEG:
                $ext = 'jpg';
                break;
            case IMAGETYPE_PNG:
                $ext = 'png';
                break;
        }

        $full_path = $path . ".$ext";

        $fp = fopen($full_path, 'w');
        if(!$fp) throw new CoreException("Failed to fopen($full_path, 'w')");

        if(!fwrite($fp, $contents))
            throw new CoreException("Failed to fwrite picture");

        fclose($fp);
        chmod($full_path, 0760);

        return $full_path;
    }

    public static function upload($file, $path) {

        global $VALID_IMG_TYPES;
        global $VALID_IMG_TYPES_STR;

        $size = $file['size'];

        if($size > MUSDB_MAX_IMAGE_SIZE)
            throw new Exception(_('Image can be ') . (MUSDB_MAX_IMAGE_SIZE / 1024) . _(' KB max.'));

        $data = getimagesize($file['tmp_name']);

        if(!in_array($data[2], $VALID_IMG_TYPES))
            throw new Exception(_('Valid image types are ') . $VALID_IMG_TYPES_STR);

        switch($data[2]) {
            case IMAGETYPE_JPEG:
                $ext = 'jpg';
                break;
            case IMAGETYPE_PNG:
                $ext = 'png';
                break;
        }

        $full_path = $path . ".$ext";

        if(!move_uploaded_file($file['tmp_name'], $full_path))
            throw new CoreException("Failed to move_uploaded_file(".$file['tmp_name'].", $full_path)");

        return $full_path;
    }

    public static function generateThumbnail($path, $width = 200, $height = 200) {

        $img = new Zubrag_image;
        $img->max_x        = $width;
        $img->max_y        = $height;
        $img->cut_x        = 0;
        $img->cut_y        = 0;
        $img->quality      = 100;
        $img->save_to_file = true;
        $img->image_type   = -1;

        return ($img->GenerateThumbFile($path, $path));
    }
}